package es.battleship.service;

import java.util.logging.Logger;

import org.springframework.stereotype.Service;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

import es.battleship.api.service.GameNotificationService;
import es.battleship.resource.GameResource;

@Service
public class GameNotificationServiceImpl implements GameNotificationService {
	Logger  logger = Logger.getLogger(GameResource.class.getName());

	private XMPPService xmpp = XMPPServiceFactory.getXMPPService();

	@Override
	public void invite(String user1, String user2) {
		logger.info("invite" + user1 + " " + user2);
		
		JID jid = new JID(user2);
		
		
		
		String text = buildInvite( user1,  user2);
		
		Message msg = new MessageBuilder()
        					.withRecipientJids(jid)
        					.withBody(text)
        					.build();
		
		
		
	     
	     logger.info("Is available " + xmpp.getPresence(jid).isAvailable());
	     if (xmpp.getPresence(jid).isAvailable()) {
            SendResponse status = xmpp.sendMessage(msg);
            if (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS) {
            	logger.info("Message sent!");
            } else {
            	logger.info(status.toString());
            }
	     }
		
	}

	@Override
	public void accept(String user1, String gameId) {
		logger.info("accept " + user1 + " " + gameId);
		
		JID jid = new JID(user1);
		
		String text = buildAccept( user1,  gameId);
		
		Message msg = new MessageBuilder()
        					.withRecipientJids(jid)
        					.withBody(text)
        					.build();
		
	     
	     logger.info("Is available " + xmpp.getPresence(jid).isAvailable());
	     if (xmpp.getPresence(jid).isAvailable()) {
            SendResponse status = xmpp.sendMessage(msg);
            if (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS) {
            	logger.info("Message sent!");
            } else {
            	logger.info(status.toString());
            }
	     }
		
	}
	
	private String buildInvite(String user1, String user2) {
	
		String msg = "{\"jsonrpc\": \"2.0\", \"method\": \"invite\", \"params\": {\"user1\": "+ user1 + ", \"user2\": "+ user2 + "}}";
		
		return msg;
	}
	
	private String buildAccept(String user1, String gameId) {
		
		String msg = "{\"jsonrpc\": \"2.0\", \"method\": \"accept\", \"params\": {\"user1\": "+ user1 + ", \"gameId\": "+ gameId + "}}";
		
		return msg;
	}

}
